<template>
    <SearchForm  @handleReset="resetForm()" @handleSearch="onSubmit()">
    <el-form :inline="true" :model="labelQueryForm" class="tableButton">
      <el-form-item>
        <el-input v-model="labelQueryForm.labelName" placeholder="请输入标签名称" clearable />
      </el-form-item>
    </el-form>
    <template #header>
        <el-button type="primary" @click="onAddOrUpdate()">新增</el-button>
    </template>
  </SearchForm>
    <el-scrollbar>
      <div class="table">
      <el-table :data="tableData" border stripe width="100%">
        <!-- <el-table-column label="ID" prop="id" align="center" width="100"/> -->
        <el-table-column label="标签名称" prop="labelName" align="center"/>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="onAddOrUpdate(scope.row)" :disabled="scope.row.id === 1 || scope.row.id === 2">编辑</el-button>
            <el-button type="danger" link @click="onDelete(scope.row)" :disabled="scope.row.id === 1 || scope.row.id === 2" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    </el-scrollbar>

  <el-dialog v-model="isShowDialog" :title="updateForm.id ? '编辑' : '新增'" width="600">
    <!-- 校验规则为rules，直接定义所有参数的rules，但是<el-form-item>中的prop还是要设置，且还需要新增一个interface -->
    <el-form ref="updateFormRef" :model="updateForm" :rules="rules">
      <el-form-item label="标签名称" :label-width="formLabelWidth" prop="labelName">
        <el-input v-model="updateForm.labelName" placeholder="请输入标签名称"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="submitUpdateForm(updateFormRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive,ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { postWithToken } from '~/composables/utils';

// 列表查询的form
const labelQueryForm = reactive({
  labelName: ''
});
const labelList = ref<Label[]>();
const getlabelList = async () => {
  const response = await postWithToken('/label/queryLabel', {});
  if (response.code == 200) {
      labelList.value = response.data;
    }
}
interface Label {
  id: number,
  labelName: string
}
getlabelList();

const tableData = ref<any>(null);
// 展示弹框的参数
const isShowDialog = ref(false);
// 弹框里面label的宽度
const formLabelWidth = '80px';

// 弹框里面的form对应的interface
interface UpdateRuleForm {
  id: number | null;
  labelName: string | null;
}
// 弹框里面的form
const updateForm = reactive<UpdateRuleForm>({
    id:null,
    labelName: null
});

const updateFormRef = ref<FormInstance>();
// 弹框的form校验规则
const rules = reactive<FormRules<UpdateRuleForm>>({
  labelName: [
    { required: true, message: '标签名称不能为空', trigger: 'blur'}
  ],
})

// 重置
const resetForm = () => {
  labelQueryForm.labelName = '';
}

// 分页查询
const onSubmit = async () => {
  try {
    const response = await postWithToken('/label/queryLabel', labelQueryForm);
    if (response.code != 200) {
      ElMessage.error(response.msg);
    } else {
      // 设置表数据
      tableData.value = response.data;
    }
  } catch (error) {
    console.error('There was an error!', error);
  }
};

// 新增或更新的弹框输入框赋值
const onAddOrUpdate = (data?: any) => {
  // 展示弹框
  isShowDialog.value = true;
  if (data != undefined) {
    updateForm.id = data.id;
    updateForm.labelName = data.labelName;
  }
};

// 新增更新数据
const addOrUpdateTopic =  async () => {
  try {
    var url = '/label/saveLabel';
    if (updateForm.id) {
      url = '/label/updateLabel';
    }
    const response = await postWithToken(url, updateForm);
    if (response.code != 200) {
        ElMessage.error(response.msg);
    }
    closeDialog();
    onSubmit();
  } catch (error) {
    console.error('There was an error!', error);
  }
};

function closeDialog() {
  isShowDialog.value = false;
  clearForm(updateFormRef.value);
}
// 重置数据
const clearForm = (formEl: FormInstance | undefined) => {
  updateForm.id = null;
  if (!formEl) return
  formEl.resetFields()
}

// 删除数据
const onDelete = async (data?: any) => {
  try {
    const response = await postWithToken('/label/deleteLabel', data);
    if (response.code != 200) {
      ElMessage.error(response.msg);
    }
    onSubmit();
  } catch (error) {
    console.error('There was an error!', error);
  }
}

// 打开页面就执行一次查询
onSubmit();

const submitUpdateForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      addOrUpdateTopic();
    } else {
      console.log('error submit!')
    }
  })
}
</script>

<style lang="scss">
/* 为了页面刷新不出现滚动条 */
.ep-scrollbar {
  height: auto;
}
</style>